package cn.element.io.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 实现NIO的通信客户端实现
 */
public class Client {

    // 1.定义客户端相关属性
    private Selector selector;
    
    private static final int PORT = 8848;
    
    private SocketChannel socketChannel;

    // 2.初始化客户端
    public Client() {
        try {
            // 创建选择器
            selector = Selector.open();
            
            // 连接服务器
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
            
            // 设置非阻塞模式
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            System.out.println("当前客户端准备完成: ");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void readInfo() throws IOException {
        while (selector.select() > 0) {
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            
            while (it.hasNext()) {
                SelectionKey key = it.next();
                
                if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    sc.read(buffer);
                    System.out.println(new String(buffer.array(), 0, buffer.remaining()));
                }
                
                it.remove();
            }
        }
    }

    private void send(String s) {
        try {
            socketChannel.write(ByteBuffer.wrap(("洛必达: " + s).getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        Client client = new Client();
        
        // 定义一个线程负责监听服务端发送过来的消息事件
        new Thread(() -> {
            try {
                client.readInfo();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            client.send(s);
        }
    }

    

}
